import 'package:dio/dio.dart';

import '../config/api_constants.dart';

class AuthInterceptor extends Interceptor {
  final Future<String?> Function() getAccessToken;
  final Future<String> Function() refreshToken;

  AuthInterceptor({
    required this.getAccessToken,
    required this.refreshToken,
  });

  @override
  Future<void> onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) async {
    final token = await getAccessToken();
    if (token != null) {
      options.headers['Authorization'] = 'Bearer $token';
    }
    handler.next(options);
  }

  @override
  Future<void> onError(
    DioException err,
    ErrorInterceptorHandler handler,
  ) async {
    if (err.response?.statusCode == ApiConstants.invalidTokenCode) {
      try {
        final newToken = await refreshToken();
        final request = err.requestOptions;
        request.headers['Authorization'] = 'Bearer $newToken';
        final response = await Dio().fetch(request);
        handler.resolve(response);
      } catch (e) {
        handler.reject(err);
      }
    } else {
      handler.next(err);
    }
  }
}
